package quake;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.ajp.Ajp13SocketConnector;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;

public class Starter {
    private static final Log log = LogFactory.getLog(Starter.class);

    private static final String STANDALONE = "standalone";
    private static final int AJP13_SOCKET_PORT = 8009;

    /**
     * @param args
     */
    public static void main(String[] args) {
        String war = "";
        boolean standalone = false;
        int selectChannelPort = 0;

        switch (args.length) {
        case 1:
            war = args[0];
            break;
        case 3:
            war = args[0];
            if (args[1].equals(STANDALONE)) {
                standalone = true;
                selectChannelPort = Integer.valueOf(args[2]);
            }
            break;
        default:
            log.error("quake parameter error. num = " + args.length);
            System.exit(-1);
            break;
        }

        Server server = new Server();

        if (standalone) {
            SelectChannelConnector connector = new SelectChannelConnector();
            connector.setPort(selectChannelPort);
            server.setConnectors(new Connector[] { connector });
        } else {
            Connector connector = new Ajp13SocketConnector();
            connector.setPort(AJP13_SOCKET_PORT);
            server.setConnectors(new Connector[] { connector });
        }

        WebAppContext web = new WebAppContext();
        web.setContextPath("/");
        web.setWar(war);

        server.addHandler(web);

        try {
            server.start();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(100);
        }

        System.exit(0);
    }
}
